﻿using Pb;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using cn.sharesdk.unity3d;
using UnityEngine.SceneManagement;

public class NetWorkAbnormal : Game
{
    EginDN dn = EginDN.Instance;
    public string ConcentIP = "192.168.1.138";// "192.168.1.138";   // 116.62.190.213   // 192.168.1.108测试 //192.168.1.138:3572
    public string ConcentPort = "3572";
    public UILabel AbnormalText; 
    EginUser user = EginUser.Instance;
    EginMahjong mahjong = EginMahjong.Instance;
    SoundModel soundModel;

    private ShareSDK ssdk;
    private void Awake()
    {
        ssdk = GameObject.Find("SoundManger").GetComponent<ShareSDK>();
        ssdk.authHandler = OnAuthResultHandler;
        ssdk.shareHandler = OnShareResultHandler;
        ssdk.showUserHandler = OnGetUserInfoResultHandler;

        if (user.userKickOutMessage != null)
        {
            AbnormalText.text = "你的账号异地登录," + "IP:" + user.userKickOutMessage.Ip;
            //TimeText.gameObject.SetActive(false);
        }
        else
        {
            AbnormalText.text = "网络异常，请重新连接...";
        }
        soundModel = GameObject.Find("SoundManger").GetComponent<SoundModel>();
    }
    
    
    public void Reconect()
    {
        user.RecentTimes++;
        SocketManager.Instance.socketListener = null;
        StartCoroutine(loadScene());
        Debug.Log("重连1");

    }
    IEnumerator loadScene()
    {
        StartFunc();
        yield return null;
    }
    protected void StartFunc()
    {
        StartCoroutine(StartGame());
    }
    protected IEnumerator StartGame()
    {
        SocketConnectInfo connectInfo = SocketConnectInfo.Instance;
        connectInfo.roomHost = ConcentIP; // 116.62.190.213   // 192.168.1.108测试
        connectInfo.roomPort = ConcentPort;
        SocketManager socketManager = SocketManager.Instance;
        yield return socketManager;
        socketManager.ConnectTest(connectInfo);
        base.StartGameSocket();
        SocketManager.Instance.socketListener = this;
    }
    public override void SocketReceiveMessage(byte[] data)
    {

        base.SocketReceiveMessage(data);
        byte[] dataLength = data.Skip(0).Take(2).ToArray();
        byte[] dataId = data.Skip(2).Take(2).ToArray();
        byte[] dataConcent = data.Skip(data.Length - (data.Length - 4)).ToArray();
        int TempMsgID = ProtoDataToMsg.Byte2ushort(dataId);
        if (TempMsgID == MsgId.CheckinResponse)
        {
            Pb.CheckinResponse newpb = Pb.CheckinResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            //存储checkin返回消息

            user.ddzRoomList = newpb.DdzRoomList.ToList();
            user.mahjongRoomList = newpb.MahjongRoomList.ToList();
            user.nnRoomList = newpb.NnRoomList.ToList();
            user.pdkRoomList = newpb.RunRoomList.ToList();         


            user.ddzRoomList = newpb.DdzRoomList.ToList();
            user.mahjongRoomList = newpb.MahjongRoomList.ToList();
            user.nnRoomList = newpb.NnRoomList.ToList();
            user.pdkRoomList = newpb.RunRoomList.ToList();

            //user.serviceWeixin = newpb.ServiceWeixin;
            user.ddzRoomList = newpb.DdzRoomList.ToList();
            user.mahjongRoomList = newpb.MahjongRoomList.ToList();
            user.nnRoomList = newpb.NnRoomList.ToList();
            //user.pdkRoomList = newpb.FlowerRoomList.ToList();

            Debug.Log("user.loginControl = " + user.loginControl);
            if(user.loginControl == 1){
                WXLgoin();
            }
            else
            {
                LoginEvent();
            }
             
            
            
        }
        #region  登录
        //处理登录后消息
        else if (TempMsgID == MsgId.LoginResponse)
        {
            Pb.LoginResponse newpb = Pb.LoginResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);

            if (newpb.Status == STATUS.Success)
            {
                user.Uid = newpb.UserInfo.Uid.ToString();
                user.IP = newpb.UserInfo.Ip;
                user.nickname = newpb.UserInfo.Nickname;
                user.coinCount = newpb.UserInfo.BagCoinCount.ToString();
                user.sex = newpb.UserInfo.Sex;
                user.avatarId = newpb.UserInfo.AvatarId;
                //Application.LoadLevelAsync(ScenePath.Hall);
                //登录成功后要进行重连判断
                #region 麻将存储
                mahjong.nickname = newpb.UserInfo.Nickname;
                mahjong.uid = newpb.UserInfo.Uid;
                mahjong.sex = newpb.UserInfo.Sex;
                mahjong.coinCount = newpb.UserInfo.BagCoinCount;
                mahjong.Score = newpb.UserInfo.Score;
                mahjong.openRoomId = newpb.GameRoomId;
                mahjong.gameRoomId = newpb.GameRoomId;
                // mahjong.win_rate = newpb.UserInfo.GameInfoList[0].WinRate;
                // mahjong.GameType = newpb.UserInfo.GameInfoList[0].GameType.ToString();
                mahjong.seatStatus = newpb.UserInfo.SeatStatus;
                mahjong.Avatar_id = newpb.UserInfo.AvatarId;
                mahjong.IP = newpb.UserInfo.Ip;
                #endregion


                user.gameType = newpb.GameTypeId;

                if (newpb.GameTypeId == 101)
                {
                    EginXTJ.Instance.roomId = newpb.GameRoomId;
                }

                if (newpb.GameRoomId != 0)
                {
                    reconnect(newpb.GameTypeId);
                    user.gameType = (newpb.GameTypeId);

                }
                else
                {
                    Application.LoadLevelAsync("Hall");//不用异步会卡死 暂时不知道什么原因-------
                }
            }
            else
            {
                user.logMsg = newpb.Msg;
                //LoadModel("LogMsg");
            }
        }
        #endregion

        #region  重连返回消息
        //处理登录后消息
        else if (TempMsgID == MsgId.NnReconnectRoomResponse)
        {
            Pb.NnReconnectRoomResponse newpb = Pb.NnReconnectRoomResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            NnReconnectRoomResponse(newpb);
        }
        else if (TempMsgID == MsgId.DdzReconnectRoomResponse)
        {
            Pb.DdzReconnectRoomResponse newpb = Pb.DdzReconnectRoomResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            DdzReconnectRoomResponse(newpb);
        }
        else if (TempMsgID == MsgId.MahjongReconnectRoomResponse)
        {
            Pb.MahjongReconnectRoomResponse newpb = Pb.MahjongReconnectRoomResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            MahjongReconnectRoomResponse(newpb);
        }
        else if (TempMsgID == MsgId.RunReconnectRoomResponse)
        {
            Pb.RunReconnectRoomResponse newpb = Pb.RunReconnectRoomResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            RunReconnectRoomResponse(newpb);
        }
        else if (TempMsgID == MsgId.Nn100ReconnectResponse)
        {
            Pb.Nn100ReconnectResponse newpb = Pb.Nn100ReconnectResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Nn100ReconnectResponse(newpb);
        }
        else if (TempMsgID == MsgId.PaiEnterRoundResponse)
        {
            Pb.PaiEnterRoundResponse newpb = Pb.PaiEnterRoundResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            XTJ100ReconnectResponse(newpb);
        }
        #endregion
        else if (TempMsgID == MsgId.NetWorkAbnormalMessage)
        {
            Destroy(gameObject);
            GameObject NetWorkAbnormal = NGUITools.AddChild(GameObject.Find("UI Root").gameObject, (GameObject)(Resources.Load("NetWorkAbnormal")));
        }
    }


    void LoginEvent()
    {
        string tempUserName = PlayerPrefs.GetString("EginUsername", "");
        string tempPassword = PlayerPrefs.GetString(tempUserName, "");
        string username = ProtoDataToMsg.stringToUTF8(tempUserName);
        string nickname = null;
        string passwd = ProtoDataToMsg.stringToUTF8(DataSet.StringToMd5(tempPassword));

        string dev_name = SystemInfo.deviceModel; ProtoDataToMsg.stringToUTF8(SystemInfo.deviceModel);     //SystemInfo.deviceModel; ProtoDataToMsg.stringToUTF8(SystemInfo.deviceModel)  //ProtoDataToMsg.stringToUTF8("小米");  
        string dev_number = SystemInfo.deviceUniqueIdentifier;



        if (username.Length != 0 && passwd.Length != 0)
        {
            LoginRequest lg = new Pb.LoginRequest { Username = username, Passwd = passwd,  DevName = dev_name, DevNumber = dev_number };

            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.LoginRequest);
        }
    }
    

    /// <summary>
    /// 重连
    /// </summary>
    /// <param name="GameRoomId"></param>
    void reconnect(int GameRoomId)
    {

        if (GameRoomId == 1)
        {
            mahjong.OverRoundScore.Clear();
            mahjong.TotalScore.Clear();
            mahjong.OverRank.Clear();
            mahjong.OverHandCardList.Clear();
            mahjong.OtherCoinCount.Clear();
            mahjong.OtherScore.Clear();
            mahjong.currentRound = 0;
            mahjong.OverRecordList.Clear();
            mahjong.OverRobot.Clear();
            mahjong.Otheruid.Clear();
            mahjong.OtherSeatId.Clear();
            mahjong.OtherSeatStatus.Clear();
            mahjong.OtherSex.Clear();
            mahjong.OtherIP.Clear();
            mahjong.OtherNickName.Clear();
            mahjong.OtherAvatarid.Clear();
            mahjong.bankerSid = 0;
            mahjong.mahjongSpecialCardItem.Clear();
            //发送麻将重连
            MahjongReconnectRoomRequest lg = new Pb.MahjongReconnectRoomRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.MahjongReconnectRoomRequest);
        }
        else if (GameRoomId == 2)
        {
            //发送牛牛重连
            NnReconnectRoomRequest lg = new Pb.NnReconnectRoomRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.NnReconnectRoomRequest);

        }
        else if (GameRoomId == 3)
        {

            //发送斗地主重连
            DdzReconnectRoomRequest lg = new Pb.DdzReconnectRoomRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.DdzReconnectRoomRequest);
        }
        else if (GameRoomId == 4)
        {
            //发送跑得快重连
            RunReconnectRoomRequest lg = new Pb.RunReconnectRoomRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.RunReconnectRoomRequest);

        }
        else if (GameRoomId == 100)
        {
            //发送百人牛牛重连
            Nn100ReconnectRequest lg = new Pb.Nn100ReconnectRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.Nn100ReconnectRequest);
            Debug.Log("发送牛牛百人场的重连消息");
        }
        else if (GameRoomId == 101)
        {
            PaiEnterRoundRequest pr = new Pb.PaiEnterRoundRequest { RoundId = EginXTJ.Instance.roomId };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(pr, MsgId.PaiEnterRoundRequest);
        }
    }
    /// <summary>
    /// 牛牛重连处理
    /// </summary>
    /// <param name="newpb"></param>
    void NnReconnectRoomResponse(NnReconnectRoomResponse newpb)
    {
        if (newpb.Status == STATUS.Success)
        {
            dn.seatId = newpb.SeatId;
            dn.bankerSid = newpb.BankerSid;
            dn.createrUid = newpb.RoomInfo.CreaterUid;
            dn.roomId = newpb.RoomInfo.RoomId;
            if (newpb.RoomInfo.IsCardRoom)
            {
                user.ControlScene = 1;
            }
            else
            {
                user.ControlScene = 2;
            }
            dn.MaxBankerMultiple = newpb.MaxBankerMultiple;
            dn.MaxBankerMultiple = newpb.MaxPlayerMultiple;
            dn.isReconnect = true;
            user.gameUserInfoList = newpb.UserList.ToList();
            dn.nnReconnectRoomResponse = newpb;
            soundModel.SwitchBgMusic(user.gameType);
            Application.LoadLevelAsync(ScenePath.GameDNPlay);
        }
        else
        {
            user.logMsg = newpb.Msg;
            GameObject logmsg = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("LogMsg")));
        }
    }
    /// <summary>
    /// 斗地主重连消息
    /// </summary>
    /// <param name="newpb"></param>
    void DdzReconnectRoomResponse(DdzReconnectRoomResponse newpb)
    {
        EginDDZ ddz = EginDDZ.Instance;
        // EginUser user = EginUser.Instance;
        if (newpb.Status == STATUS.Success)
            if (newpb.Status == STATUS.Success)
            {
                ddz.roomStatus = newpb.RoomInfo.RoomStatus;
                ddz.roomId = newpb.RoomInfo.RoomId;
                ddz.seatId = newpb.SeatId;
                ddz.SortSeatId();
                ddz.lordSid = newpb.LordSid;
                ddz.nextSid = newpb.TurnSid;
                ddz.createrUid = newpb.RoomInfo.CreaterUid;

                user.gameUserInfoList = newpb.UserInfoList.ToList();
                if (newpb.RoomInfo.IsCardRoom)
                {
                    user.ControlScene = 1;
                }
                else
                {
                    user.ControlScene = 2;
                }

                ddz.ddzReconnectRoomResponse = newpb;
                ddz.isReconnect = true;
                soundModel.SwitchBgMusic(user.gameType);
                Application.LoadLevelAsync(ScenePath.GameDDZPlay);
            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject logmsg = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("LogMsg")));
            }
    }
    /// <summary>
    /// 麻将重连
    /// </summary>
    /// <param name="newpb"></param>
    void MahjongReconnectRoomResponse(MahjongReconnectRoomResponse newpb)

    {
        if (newpb.RoomInfo.IsCardRoom)
        {
            user.ControlScene = 1;
        }
        else
        {
            user.ControlScene = 2;
        }
        if (newpb.RoomInfo.RoomStatus == ROOM_STATUS.Gaming)
        {
            mahjong.gameRecent = true;
        }
        else
        {
            mahjong.gameRecent = false;
        }
        //mahjong.roomTypeId = newpb.RoomInfo.RoomTypeId;
        mahjong.CteatrUid = newpb.RoomInfo.CreaterUid;
        mahjong.roomID = newpb.RoomInfo.RoomId;
        mahjong.baseScore = newpb.RoomInfo.BaseScore;
        mahjong.roomStatus = newpb.RoomInfo.RoomStatus;
        mahjong.currentRound = newpb.RoomInfo.CurrentRound;
        mahjong.CardList = newpb.CardList.ToList();
        mahjong.turnSid = newpb.TurnSid;
        mahjong.nextSid = newpb.TurnSid;
        mahjong.seatID = newpb.SeatId;
        mahjong.remainCount = newpb.RemainCount;
        mahjong.handCard = newpb.HandCard;
        mahjong.tableCard = newpb.TableCard;
        mahjong.bankerSid = newpb.BankerSid;
        mahjong.LastBankSid = newpb.BankerSid;            //一定要在重连也存储否则会显示两个庄
        mahjong.isSpecialPhases2 = newpb.IsSpecialPhases2;

        mahjong.LastSeatID = newpb.LastSid;   //给cardmodel用
                                              //user.uid=newpb.UserInfoList.
                                              //存储其他玩家信息

        mahjong.tingCards = newpb.ReadyCards.ToList();
        mahjong.Otheruid = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.Uid);
        mahjong.OtherSeatId = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.SeatId);
        mahjong.OtherSeatStatus = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.SeatStatus);
        mahjong.OtherSex = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.Sex);
        mahjong.OtherIP = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.Ip);
        mahjong.OtherCoinCount = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.BagCoinCount);
        mahjong.OtherScore = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.Score);
        mahjong.OtherNickName = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.Nickname);
        mahjong.OtherAvatarid = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.AvatarId);
        mahjong.OtherOutCardList = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.OutCardList.ToList());
        mahjong.mahjongDoneSpecialCard = newpb.SpecialDoneList.ToList();
        mahjong.OverRecordList = newpb.ScoreList.ToDictionary(t => t.RoundId, t => t.ScoreRoundList.ToList());  //重连后存储玩家的游戏结束分数     
        mahjong.TotalScore = newpb.UserInfoList.ToDictionary(t => t.SeatId, t => t.Score);
        //Debug.Log("存储其他玩家信息" + user.OtherCoinCount[1]);

        if (newpb.SpecialListReady.Count != 0)
        {
            mahjong.mahjongSpecialCardItem = newpb.SpecialListReady.ToList();
        }
        if (newpb.SpecialSid > 0)
        {
            mahjong.nextSid = newpb.SpecialSid;
            mahjong.turnSid = newpb.SpecialSid;
        }
        user.gameUserInfoList = newpb.UserInfoList.ToList();
        Application.LoadLevel("GameMahjongPlay");
    }
    /// <summary>
    /// 跑得快重连处理
    /// </summary>
    /// <param name="newpb"></param>
    void RunReconnectRoomResponse(RunReconnectRoomResponse newpb)
    {
        if (newpb.Status == STATUS.Success)
        {
            EginPDK pdk = EginPDK.Instance;
            pdk.createrUid = newpb.RoomInfo.CreaterUid;
            //pdk.bankerSid = newpb.BankerSid;
            pdk.roomId = newpb.RoomInfo.RoomId;
            pdk.currentRound = newpb.RoomInfo.CurrentRound;
            pdk.baseScore = newpb.RoomInfo.BaseScore;
            pdk.totalRound = newpb.RoomInfo.TotalRound;
            pdk.roomStatus = newpb.RoomInfo.RoomStatus;
            user.gameUserInfoList = newpb.UserInfoList.ToList();
            Debug.Log("房间内有" + user.gameUserInfoList.Count + "个玩家");

            //判定是不是好友场
            if (newpb.RoomInfo.IsCardRoom)
            {
                user.ControlScene = 1;
                pdk.isCardRoom = true;
            }
            else if (newpb.RoomInfo.IsCardRoom == false && newpb.RoomInfo.TotalRound > 0)
            {
                user.ControlScene = 1;
                pdk.isCardRoom = false;
            }
            else
            {
                user.ControlScene = 2;
            }

            pdk.isReconnect = true;
            pdk.runReconnectRoomResponse = newpb;
            soundModel.SwitchBgMusic(user.gameType);
            Application.LoadLevelAsync(ScenePath.GamePDKPlay);
        }
        else
        {
            user.logMsg = newpb.Msg;
            GameObject Set = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("LogMsg")));
        }
    }

    /// <summary>
    /// 百人牛牛重连
    /// </summary>
    /// <param name="newpb"></param>
    void Nn100ReconnectResponse(Nn100ReconnectResponse newpb)
    {
        if (newpb.Status == STATUS.Success)
        {

            dn.bankerInfo = newpb.BankerUserInfo;
            dn.chairUserList = newpb.ChairUserList.ToList();
            dn.chipInfo = newpb.ChipInfo;
            dn.isReconnect = true;
            user.gameUserInfoList = newpb.UserInfoList.ToList();
            Debug.Log("重新连接：" + newpb.UserInfoList.Count);
            dn.nn100ReconnectResponse = newpb;
            //soundModel.SwitchBgMusic(user.gameType);
            Application.LoadLevelAsync(ScenePath.GameDNPlay100);
        }
        else
        {
            user.logMsg = newpb.Msg;
            GameObject Set = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("LogMsg")));
        }

    }

    /// <summary>
    /// 天九重连
    /// </summary>
    /// <param name="newpb"></param>
    void XTJ100ReconnectResponse(PaiEnterRoundResponse newpb)
    {
        EginXTJ xtj = EginXTJ.Instance;
        if (newpb.Status == (int)STATUS.Success)
        {
            xtj.newpb = newpb;
            xtj.playersList = newpb.Round.PlayerInfo.ToList();
            xtj.roomStatus = newpb.Round.Status;
            xtj.currentRound = newpb.Round.Total;
            xtj.roomId = newpb.Round.RoundNumber;
            xtj.roundId = newpb.Round.Id;
            Debug.Log("房间ID：" + newpb.Round.RoundNumber);
            xtj.level = newpb.Round.Level;
            Debug.Log("房间Level：" + newpb.Round.Level);
            xtj.roundType = newpb.Round.RoundType;
            xtj.chipList = newpb.Round.ChipLevels.ToList();
            xtj.cardHistory = newpb.Round.CardHistory.ToList();
            xtj.roundCardNum = xtj.cardHistory.Count / 8;
            xtj.roundNum = newpb.Round.Total;
            xtj.playersNum = newpb.Round.OnlineNumber;
            xtj.roundType = newpb.Round.RoundType;
            xtj.createrUid = newpb.Round.CreatorId;
            xtj.bankerId = newpb.Round.MasterInfo.Id;
            soundModel.SwitchBgMusic(5);

            xtj.bankerInfo = newpb.Round.MasterInfo;
            if (newpb.Round.RoundType == 1)
            {
                SceneManager.LoadSceneAsync(ScenePath.GameXTJ);
            }
            else if (newpb.Round.RoundType == 3)
            {
                SceneManager.LoadSceneAsync(ScenePath.GameXTJOfFriend);
            }
            else if (newpb.Round.RoundType == 4)
            {
                SceneManager.LoadSceneAsync(ScenePath.GameXTJ100);
            }
        }
        else
        {
            user.logMsg = newpb.Msg;
            GameObject Set = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("LogMsg")));
        }

    }


    void WXLgoin()
    {
        user.loginControl = 1;
        if (Application.platform == RuntimePlatform.Android ||
        Application.platform == RuntimePlatform.IPhonePlayer)
        {
            //myDebug.text = "登录中";
            ssdk.CancelAuthorize(PlatformType.WeChat);
            ssdk.Authorize(PlatformType.WeChat);

            return;
        }
        else
        {


        }
    }

    void OnAuthResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
    {

        Debug.Log("授权中");
        //myDebug.text = "授权中";
        if (state == ResponseState.Success)
        {
            print("authorize success !" + "Platform :" + type);
            Debug.Log("授权成功");
            //myDebug.text = "授权成功";
            ssdk.GetUserInfo(PlatformType.WeChat);
        }
        else if (state == ResponseState.Fail)
        {
#if UNITY_ANDROID
            print("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
#elif UNITY_IPHONE
			print ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
#endif
        }
        else if (state == ResponseState.Cancel)
        {
            print("cancel !");
        }
    }

    void OnShareResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
    {
        if (state == ResponseState.Success)
        {
            print("share successfully - share result :");
            print(MiniJSON.jsonEncode(result));
        }
        else if (state == ResponseState.Fail)
        {
#if UNITY_ANDROID
            print("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
#elif UNITY_IPHONE
			print ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
#endif
        }
        else if (state == ResponseState.Cancel)
        {
            print("cancel !");
        }
    }

    void OnGetUserInfoResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
    {
        if (state == ResponseState.Success)
        {
            /*          
          { 
          "openid":"OPENID",
          "nickname":"NICKNAME",
          "sex":1,
          "province":"PROVINCE",
          "city":"CITY",
          "country":"COUNTRY",
          "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
          "privilege":[
          "PRIVILEGE1", 
          "PRIVILEGE2"
          ],
          "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"

          }
          openid	普通用户的标识，对当前开发者帐号唯一
          nickname	普通用户昵称
          sex	普通用户性别，1为男性，2为女性
          province	普通用户个人资料填写的省份
          city	普通用户个人资料填写的城市
          country	国家，如中国为CN
          headimgurl	用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像），用户没有头像时该项为空
          privilege	用户特权信息，json数组，如微信沃卡用户为（chinaunicom）
          unionid	用户统一标识。针对一个微信开放平台帐号下的应用，同一用户的unionid是唯一的。
            
          
           
            PlayerPrefs.SetString("faceurl", result["headimgurl"] as string);
            string sex = "";
            sex = result["sex"].ToString();      
            int ht = int.Parse(sex);           
            PlayerPrefs.SetInt("ht", ht);            
            Debug.Log("数据获取成功");
            PlayerPrefs.SetString("name", result["nickname"] as string);
            //存储发送登录消息
            GetUserInfoAndSendLogin(result);*/
            //myDebug.text = "数据获取成功";
            Debug.Log("数据获取成功");
            //存储用户信息
            Debug.Log("headimgurl:" + result["headimgurl"] as string);
            Debug.Log("sex:" + result["sex"] as string);
            Debug.Log("nickname:" + result["nickname"] as string);
            Debug.Log("unionid:" + result["unionid"] as string);
            //DeBug.text = MiniJSON.jsonEncode(result);
            Debug.Log(MiniJSON.jsonEncode(result));
            //DeBug.text += "headimgurl:" + result["headimgurl"] as string + "\t";

            //DeBug.text += "sex:" + result["sex"] as string + "\t";

            //DeBug.text += "nickname:" + result["nickname"] as string + "\t";

            //DeBug.text += "unionid:" + result["unionid"] as string;
            Debug.Log("输出完毕");
            string sex = "";
            sex = result["sex"].ToString();
            int ht = int.Parse(sex);
            if (ht == 0 || ht == 1)
            {
                user.sex = SEX.Male;
            }
            else
            {
                user.sex = SEX.Female;
            }

            Debug.Log("性别加载完毕");
            user.Uid = result["unionid"] as string;
            user.nickname = result["nickname"] as string;
            //用户的url获取
            //user.a = result["headimgurl"] as string;

            Debug.Log("性别加载完毕");
            user.userUrl = result["headimgurl"] as string;
            StartCoroutine("GetWWWFACE", result["headimgurl"] as string);

            Debug.Log("头像加载完毕");
            //获取设备
            string dev_name = SystemInfo.deviceModel;      //SystemInfo.deviceModel; ProtoDataToMsg.stringToUTF8(SystemInfo.deviceModel)  //ProtoDataToMsg.stringToUTF8("小米");  
            string dev_number = SystemInfo.deviceUniqueIdentifier;

            Debug.Log("获取设备成功");
            //发送登录信息
            //Username = ProtoDataToMsg.stringToUTF8(user.username),
            Debug.Log("微信类型" + CHANNEL_TYPE.Weixin);
            Debug.Log("用户ID" + ProtoDataToMsg.stringToUTF8(user.Uid));
            Debug.Log(user.sex);
            Debug.Log(dev_number);
            ProtoDataToMsg.stringToUTF8("用户头像" + user.userUrl);

            LoginRequest lg = new Pb.LoginRequest { Channel = CHANNEL_TYPE.Weixin, Username = ProtoDataToMsg.stringToUTF8(user.Uid), Nickname = ProtoDataToMsg.stringToUTF8(user.nickname), Sex = user.sex, DevNumber = dev_number, AvatarUrl = ProtoDataToMsg.stringToUTF8(user.userUrl) };
            PlayerPrefs.SetString("username", ProtoDataToMsg.stringToUTF8(user.Uid));
            PlayerPrefs.SetString("nickname", ProtoDataToMsg.stringToUTF8(user.nickname));
            PlayerPrefs.SetInt("Sex", ht);
            PlayerPrefs.SetString("AvatarUrl", ProtoDataToMsg.stringToUTF8(user.userUrl));
            PlayerPrefs.SetInt("autologin", 1);
            EginUser.Instance.nickname = ProtoDataToMsg.stringToUTF8(user.nickname);
            Debug.Log("存储信息完毕");
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(lg, MsgId.LoginRequest);
            Debug.Log("发送消息完毕");
        }
        else if (state == ResponseState.Fail)
        {
#if UNITY_ANDROID
            print("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
#elif UNITY_IPHONE
			print ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
#endif
        }
        else if (state == ResponseState.Cancel)
        {
            print("cancel !");
        }
    }

}
